﻿using System;
using System.Windows.Controls;
using System.Windows.Media;
using FarseerGames.FarseerPhysics.Mathematics;
using FreeGoo.GameEngine.Renderables;
using FreeGoo.GameEngine.Renderables.Links;

namespace FreeGoo.WpfRenderer
{
    public class LinkRenderer : Renderer
    {
        public LinkRenderer(RendererFactory factory, Link link)
            : base(factory, link)
        {
            // I don't like using var - but when mixing C# and Silverlight colors, it's a blessing
            var color = RendererFactory.GetColorForLinkable(link.OwningLinkable);

            Image = factory.CreateImageForFileNameColorized(@"Resources\Link1.png", color);
            ////Image.SetValue(Panel.ZIndexProperty, 3);

            Image.Stretch = Stretch.Fill;
            Image.Width = 75;
            Image.Height = 8;
            TransformGroup transformGroup = new TransformGroup();
            RotateTransform = new RotateTransform();
            TranslateTransform = new TranslateTransform();
            transformGroup.Children.Add(RotateTransform);
            transformGroup.Children.Add(TranslateTransform);
            Image.RenderTransform = transformGroup;
            Update();
            Factory.Canvas.Children.Insert(0, Image);
        }

        public Link Link { get { return Renderable as Link; } }
        public Image Image { get; set; }
        protected RotateTransform RotateTransform { get; set; }
        protected TranslateTransform TranslateTransform { get; set; }

        public override void Update()
        {
            ////Vector2 jointStart = Link.Linkable1.Body.GetWorldPosition(Link.Joint.Anchor1);
            ////Vector2 jointEnd = Link.Linkable2.Body.GetWorldPosition(Link.Joint.Anchor2);
            Vector2 jointStart = Link.LinkStart; // Linkable1.Body.GetWorldPosition(Link.Jo);
            Vector2 jointEnd = Link.LinkEnd; // Linkable2.Body.GetWorldPosition(Link.Linkable2.Position);

            Vector2 delta = jointStart - jointEnd;
            float length = delta.Length();
            Vector2 centerPos = (jointStart + jointEnd) * 0.5f;

            Image.Width = length;
            double centerX = length * 0.5;
            double centerY = Image.Height * 0.5;

            Image.SetValue(Canvas.LeftProperty, -centerX);
            Image.SetValue(Canvas.TopProperty, -centerY);
            double rotation = Math.Atan2(delta.Y, delta.X);
            RotateTransform.Angle = (rotation * 360) / (2 * Math.PI);
            RotateTransform.CenterX = centerX;
            RotateTransform.CenterY = centerY;

            TranslateTransform.X = centerPos.X;
            TranslateTransform.Y = centerPos.Y;
        }

        public override void Delete()
        {
            Factory.Canvas.Children.Remove(Image);
        }

        public override void StateChanged()
        {
        }
    }
}
